'use strict';

const { Controller } = require('egg');

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hello World';
  }
  async register() {
    const { ctx } = this;
    // 1.获取数据
    const { user_name, password } = ctx.request.body;
    console.log(user_name, password);
    try {
      // 2.操作数据库
      const res = await ctx.service.user.createUser(user_name, password);
      // 3.返回结果
      ctx.body = {
        code: 0,
        message: '用户注册成功',
        result: {
          id: res.id,
          user_name: res.user_name,
        },
      };
    } catch (error) {
      console.error('用户注册错误', error);
      ctx.app.emit('error', 'userRegisterError', ctx);
    }
  }
  async login() {
    const { ctx } = this;
    const { user_name } = ctx.request.body;
    try {
      const { password, ...res } = await ctx.service.user.getUserInfo({
        user_name,
      });

      ctx.body = {
        code: 0,
        message: '用户登录成功',
        result: {
          token: ctx.app.jwt.sign(res, ctx.app.config.jwt.secret),
          // token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' }),
        },
      };
    } catch (error) {
      console.error('用户登录失败', error);
    }
  }

  async changePassword() {
    const { ctx } = this;

    const id = ctx.state.user.id;
    const password = ctx.request.body.password;

    if (await ctx.service.user.updateById({ id, password })) {
      ctx.body = {
        code: 0,
        message: '密码修改成功',
        result: '',
      };
    } else {
      ctx.body = {
        code: '10007',
        message: '密码修改失败',
        result: '',
      };
    }
  }
}

module.exports = UserController;
